#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/7/20 11:33
# @Author  : Samge
import datetime
import re

from PyQt5.QtWidgets import QTableWidgetItem

from itkz.resources.custom_view.BaseQWidget import BaseQWidget
from itkz.resources.utils import tip_util, config_util, qt_utils
from itkz.resources.utils.log import Log


class BaseTableWidget(BaseQWidget):

    # 是否在打开程序时自动初始化数据
    AUTO_INIT_DATA = True

    # 表查询字段名的配置
    fields_key = {
        'table_name': 'ScrapyWebLinkSource',
        'field_status': '',
        'field_dataId': '',
        'field_title': '',
        'field_order_by': '',
        'field_province': '',
        'field_city': '',
        'field_area': '',
        'field_keyword': '',
        'field_query_fields': '',
        'field_other_params': ''
    }

    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setupConfig()

    def query_senior(self):
        print("高级查询")
        custom_sql = self.filter_input.get_filter_sql
        print(custom_sql)
        self.query_source_list(custom_sql=custom_sql)
        #self.filter_input.save_config_value()

    def setupFieldsKey(self):
        for key in self.fields_key.keys():
            config_key = f"{self.name()}/{key}"
            value = config_util.value(f"{self.name()}/{key}", self.fields_key.get(key))
            self.fields_key[key] = value
            config_util.setValue(config_key, value)
        self.setupFilter()

    def setupFilter(self):
        try:
            self.filter_input.setupQSettingsName(self.name())
            self.filter_input.setupFieldsKey(self.fields_key)
        except:
            pass

    def setupConfig(self):
        """
        读取配置信息并初始化
        :return:
        """
        self.sql_history = config_util.get_sql_hist(self.name())
        self.cb_sql.addItems(self.sql_history)
        # 初始化自动查询
        if self.AUTO_INIT_DATA:
            self.query_source_list(is_init=True)
        self.setupFieldsKey()

    def query_source_list(self, custom_sql=None, is_init=False):
        """
        查询数据库
        :return:
        """
        custom_sql = '' if is_init else (custom_sql or self.cb_sql.currentText())
        if custom_sql:
            # 保存查询历史
            if custom_sql not in self.sql_history:
                self.sql_history.insert(0, custom_sql)
            else:
                curr_position = self.sql_history.index(custom_sql)
                self.sql_history[0], self.sql_history[curr_position] = self.sql_history[curr_position], \
                                                                       self.sql_history[0]
            config_util.set_sql_hist(self.name(), self.sql_history)

            # 重置下拉框选项
            self.cb_sql.clear()
            self.cb_sql.addItems(self.sql_history)

        self.setup_db()
        results = self.get_results(custom_sql) or []
        # Log().getlog().info(f"点击查询 {results}")

        if is_init and not results:
            return

        if is_init:
            fields = dict(results[0]).keys()
            try:
                self.filter_input.set_table_fields(fields)
            except:
                pass
            print(f'提取表字段:{fields}')

        self.parse_table_data(results)

    def save_curr(self):
        """
        保存（更新）当前修改数据到数据库
        :return:
        """
        Log().getlog().info(f"save_curr")
        temp_list = []
        rowCount = self.tableWidget.rowCount()
        columnCount = self.tableWidget.columnCount()
        for i in range(1, rowCount):
            item_dict = {}
            for y in range(columnCount):
                key = self.tableWidget.item(0, y).text()
                value = self.tableWidget.item(i, y)
                if value:
                    value = self.tableWidget.item(i, y).text()
                    if str(value).startswith('{') or str(value).startswith('['):
                        value = re.sub(r'\\+"', '\\"', value)
                    item_dict[key] = None if 'None' == value else value
            temp_list.append(item_dict)
        Log().getlog().info(str(temp_list).replace("'", '"').replace('None', ""))

        # 更新入库
        self.setup_db()
        tip = self.save_data_list(temp_list)
        tip_util.show_tip(self, content=tip)

    def update_data_to_db(self, temp_list, _db):
        """
        更新数据到数据库
        :param temp_list:
        :param _db:
        :return:
        """
        if not temp_list:
            return "没有需要要处理的数据，请先进行查询操作"

        fail_count = 0
        for item in temp_list:
            is_succeed = _db.update_item(item)
            if not is_succeed:
                fail_count += 1
        tip = f"成功【{len(temp_list) - fail_count}】条数据，\n" \
              f"失败【{fail_count}】条数据，\n" \
              f"总共【{len(temp_list)}】条数据。"
        return tip

    def save_data_list(self, temp_list):
        """
        【子类需要实现】更新列表数据到数据库，子类需要实现
        :param temp_list:
        :return:
        """
        return None

    def get_results(self, custom_sql):
        """
        【子类需要实现】查询数据库，获取结果列表
        :param custom_sql:
        :return:
        """
        return None

    def parse_table_data(self, results):
        """
        处理数据库查询结果的数据库展示
        :param results: 查询结果
        :return:
        """
        if not results:
            self.tableWidget.clearContents()
            tip_util.show_tip(self, content="查询结果为空，请更换查询条件重试", title="结果提示")
            return

        # 添加标题栏(表头)
        results.insert(0, results[0])
        # self.tableWidget.setHorizontalHeaderLabels(results[0])

        numrows = len(results)  # 获取列表数据的行数
        numcols = len(results[0])  # 获取列表数据的列数
        # 设置QTabWidget的行和列
        self.tableWidget.setColumnCount(numcols)
        self.tableWidget.setRowCount(numrows)

        # 这两项设置所有列平分当前窗口宽度
        # self.tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.tableWidget.horizontalHeader().setSectionResizeMode(0, QHeaderView.Interactive)

        # 遍历列表数据并添加到QTableWidget
        for row in range(numrows):  # 遍历行
            item = results[row]
            for column in range(len(item.keys())):  # 遍历列
                key = list(item.keys())[column]
                value = item.get(key)
                if row == 0:
                    # 设置标题
                    self.tableWidget.setItem(row, column, QTableWidgetItem((key)))
                else:
                    # 如果数据为datetime类型，需要转换为字符串
                    if isinstance(value, datetime.datetime):
                        self.tableWidget.setItem(row, column, QTableWidgetItem((value.strftime('%Y-%m-%d %H:%M:%S'))))
                    else:
                        # 在指定行列插入数据
                        self.tableWidget.setItem(row, column, QTableWidgetItem((str(value))))

    def table_item_double_click(self, item):
        item_text = item.text()
        Log().getlog().info(f"双击table，自动复制文本: {item_text}")
        qt_utils.open_url(self, item_text)
